
# 选课与写入成绩的业务逻辑
import json

from django.db import DatabaseError
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.views import View

from sc.models import SCInfo

class index(View):
    """ 学生选课结果 """
    def get(self, request):

        try:
            data = list(SCInfo.objects.all().
                        values('id', 'Sno', 'Cno', 'Grade', 'Sno__Sname', 'Sno__Sdept', 'Cno__Cname').
                        order_by('Sno', 'Cno'))
        except DatabaseError:
            return JsonResponse({'code': 0, 'msg': '数据获取失败'})

        return JsonResponse({'code': 200, 'msg': '数据获取成功', "data": data})


class selectInfo(View):
    """查询各学生选了哪几门课"""
    def get(self, request):
        return HttpResponse('你到底选了哪几门课呢？')

    def post(self, request):
        # 获取参数
        Sno = request.POST.get('Sno')
        # 查询数据
        try:
            # 查询出这个学号对应选出的课
            data = list(SCInfo.objects.filter(Sno=Sno).order_by('Cno').values('Cno'))
            # print(data)
        except DatabaseError:
            return JsonResponse({'code': 0, 'msg': '查询失败'})

        # 返回数据
        return JsonResponse({'code': 200, 'msg': '查询成功', 'data': data})


class updateGrade(View):
    """ 成绩更新 """
    def get(self, request):
        return HttpResponse("更新成绩啦")


    def post(self, request):
        # 接收参数
        data = request.POST.get('data')
        data = json.loads(data)
        # 更改数据
        try:
            # 更新分数
            for i in data:
                SCInfo.objects.filter(Q(Cno=i['Cno']) & Q(Sno=i['Sno'])).update(Grade=i['Grade'])
        except DatabaseError:
            return JsonResponse({'code': 0, 'msg': '更新失败'})
        # 返回结果
        return JsonResponse({'code': 200, 'msg': '成绩数据更新成功'})
